#!/usr/bin/perl -w

# This is edit.pl, part of Picture Bank.  edit.pl is intended to allow you
#+ to edit the "map" file once it has been created, in order to add 
#+ keywords, which begin with a : and searchable terms.  All terms and
#+ keywords are separated by spaces.  Picture bank currently understands
#+ the keywords :gallery-something, :new and :ignore, but others can be added.

# Copyright (C) 2007 Alexis Phoenix

# url should look like this
# edit.pl?map=test.map&path0=/a/path&edit0=this+text&path1=/another/path&edit1=more+text
#+ and so on

# 30/5/07 removed commented out code

#$config_path="./config/";
$config_path="/usr/lib/cgi-bin/config/";

use CGI;
use CGI::Pretty;
#print "content-type=text/html\n\n<html><head><title>Picture Bank</title></head>\n<body>";

$query=new CGI;
$map_file=$query->param("map");
$new_only=$query->param("new") or $new_only=0;
$ignore=$query->param("ignore") or $ignore=0;
$params=$#everything; # 19/09/08 - surely this shouldn't be here - see 8 lines down
$query->delete("submit");
$query->delete("new");
$query->delete("ignore");
$query->delete("map");
#$query_string=$query->query_string();
@everything=$query->param(); # 19/09/08 what's left after the deletions should be the things to edit
$params=$#everything;
$ADMIN='admin.pl';
$ME='edit.pl';
$SEARCH='search.pl';
$THUMBS='thumbs.pl';

print $query->header(),
      $query->start_html(-title=>'Picture Bank',lang=>'en-GB');
#print "my everything is: ".join(" ",@everything);

if (defined($map_file)) {
  $map="$config_path"."$map_file";
#  print "Go to: <a href=admin.pl>Admin page</a> <a href=search.pl?map=$map_file>Search page</a>"
  print $query->p('Go to:',
        $query->a({href=>"$ADMIN"},'Admin page').' ',
        $query->a({href=>"$SEARCH"},'Search page')
               );

}
else {
  print $query->p('no map file given.  Choose one from the ',
        $query->a({href=>"$ADMIN"},'Admin page')
                 ),
        $query->p('Quitting.'),
        $query->end_html;
  exit
}

open (MAP, "$map");
while (<MAP>) {
  $line=$_;
  chomp($line);
  push (@map,$line)
}
close (MAP);

if ($params > 0) {  # it should be at least 1 if there are edits
  print "<ul>";
  for ($i=0;scalar(@everything)>0;$i++) {
    $paths[$i]=$query->param(shift(@everything));
  #  print "got path: $paths[$i]<br>";
    $edits[$i]=$query->param(shift(@everything));
  #  print "got edit: $edits[$i]<br>";
#    print "<li>Edit ".($i+1).": Searchable terms and keywords for: $paths[$i] being changed to: $edits[$i].</li>\n";
  }
  print "</ul>\n";
  &update_map() ## get this done in case script called from elsewhere # 19/09/08 - Eh?
}

$iflag=0;
$new=0;
$tab=0;
$n=0;
#@array=();
foreach (@map) {
  $lin=$_;
  chomp($lin);
  if ($lin =~ m/:new/) {
    unless ($new==1) {
      print $query->p('New directories have been added to the album.  Add keywords and search terms below. Replace '.
                      '":new" with keyword(s) as required.  Keywords must start with a colon.  Searchable terms '.
                      'must not contain a colon.');
      $new=1
    }
  }
  unless ($tab==1) { # to ensure message (above) gets printed first if applicable
     print $query->table({-border=>0},
           $query->th({span=>2},'Valid keywords are:'),
           $query->Tr({align=>'left',valign=>'top'},
           [
           $query->td([':new','created automatically for new entries.  Ensures the line will be  made available for editing']),
           $query->td([':gallery','identifies directories that will appear together because they   have the same kind of content']),
           $query->td([':ignore','use this to make Picture Bank ignore this directory']),
           $query->td([':nothumb','not implemented yet.  So Picture Bank doesn\'t try to create thumbnails for the files']),
           $query->td([':music','not implemented yet.  Files to be played and not seen']),
           $query->td([':text','not implemented yet.  So that text files are shown appropriately']),
           ])
                        ),
          $query->hr({width=>'80%',align=>'center'});
    if ($ignore==1) {
      print $query->p('Choose to edit new items only, or all items (except ignored), here:',
            $query->a({href=>"$ME?map=$map_file&new=1&ignore=$iflag"},'New only').' | ',
            $query->a({href=>"$ME?map=$map_file&new=0&ignore=$iflag"},'All items')
                     )
    }
    elsif ($new_only==1) {
      print $query->p('If you want to edit all items (except ignored), click here:',
            $query->a({href=>"$ME?map=$map_file&new=0&ignore=$iflag"},'All items')
                     )
    }
    else {
      print $query->p('If you want to edit new items only, click here:',
            $query->a({href=>"$ME?map=$map_file&new=1&ignore=$iflag"},'New only')
                     )
    }
    print $query->start_form(-action=>"http://127.0.0.1/cgi-bin/$ME", method=>"POST"),
          $query->p(
          $query->submit(-name=>'submit',value=>'Submit changes').'&nbsp;&nbsp;',
          $query->reset,
          ),
          $query->hidden(-name=>'map',value=>"$map_file"),
          $query->hidden(-name=>'ignore',value=>"$iflag"),
          $query->hidden(-name=>'new',value=>"$new"),
          $query->start_table;
    $tab=1
  }
  
  if ($new_only==1) {
    if ($lin =~ m/:new/) {
      &printedits()
    }
  }
  else {
    &printedits()
  }
$n++
}
print $query->end_table,
      $query->p(
      $query->submit(-name=>'submit',value=>'Submit changes').'&nbsp;&nbsp;',
      $query->reset
      ),
      $query->end_form;
if ($iflag==1) {
  unless ($ignore==1) {
    print $query->p('If you wish to change any entries containing the :ignore keyword, click the link<br>',
          $query->a({href=>"$ME?map=$map_file&ignore=$iflag"},'Edit my ignored directories!')
                   )
  }
}
  print $query->p('If you need to edit any other album entries, view that entry, and edit it in the box provided'),
        $query->end_html;

sub update_map() {
  print $query->p(
        $query->em('Changing the map file...')
                  );
  my $len=$#paths;
  if ($len != $#edits) {
    print $query->p("Error.  The number of paths does not match the number of edit values. ".
                    "There are $len paths and $#edits edit values.  Stopping further action."),
          $query->end_html;
    exit;
  }
 # print "len is $len, edits is $#edits map is $#map<br>";
    my $c=0;
   # my $n=0;
  for (my $n=0;$n<=$#map;$n++) {   # do this way round to reduce iterations in certain cases
    for (my $i=0;$i<=$len;$i++) {
 #   print "paths $i is $paths[$i]<br>\n";
      $pathsi=$paths[$i];
      $pathsi=~s/\+/\\\+/g;
 #     print "matching: $pathsi with $map[$n]<br>\n";
      if ($map[$n]=~m/^$pathsi\s/) {
        @arr=split(" ",$map[$n]);
        $new_line=join(" ",$pathsi,$edits[$i]);
        unless ($map[$n]=~m/^$new_line$/) {
    #      print "map line: $map[$n] is now ";
          $map[$n]="$arr[0]"." "."$edits[$i]";
          print "$map[$n]<br>\n"
        }
        $c++;  # keep a tally of how many matches
        last  # don't check more @paths when a match is found
      }
    }
    if ($c>$len) {
      last  # don't check more @map when all @paths matched
    }
  }

  rename ($map,"$map\.old"); # in case things get messed up
  open (MAP, ">$map");
  foreach (@map) {
    print MAP "$_\n"
  }
  close(MAP);
}
sub printedits {
  @line=split(" ",$lin);
  $line0=$line00=shift(@line);  
  $line0=~tr/\+/ /;
 # print "line00 is $line00<br>\n";
  $line1=join(" ",@line);
  if ($lin=~m/:ignore/) {
    $iflag=1;
    if ($ignore==1) {
      &printlines
    }
  }
  else {
    if ($ignore==0) {
      &printlines;
    }
  }
}

sub printlines {
  print $query->Tr(
        $query->td([
        $query->a({href=>"$THUMBS?map=$map_file&paths=$line0"},$line0),
        $query->hidden(-name=>"path$n",value=>"$line00"),
        $query->textfield(-name=>"edit$n",value=>"$line1",size=>'40')
        ])
        )
}
